import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import router from '@/router'
import {allAsyncRoute,anyRoute,constantRoutes} from "@/router/routes";
import {cloneDeep} from "lodash";


const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles:[],
    buttons:[],
    routes:[]
  }
}
function filterAsyncRoutes(allAsyncRoutes,routesName){
  let asyncRoutes =  allAsyncRoutes.filter(route=>{
    //如有没有同名的直接过滤掉
    if(!routesName.includes(route.name)){
      return false;
      // console.log("找到的路由",route.name)
    }
    //判断是否有children,如果有使用递归进行查找
    if(route.children && route.children.length > 0){
      route.children =  filterAsyncRoutes(route.children,routesName)
    }
    return true
  })
  return asyncRoutes
}



// console.log(router.getRoutes())
// function addRoutes(routes) {
//   routes.forEach(route=>{
//     //给路由添加一条新的路由记录作为现有路由的子路由
//     router.addRoute(route)
//     console.log(router.getRoutes())
//   })
// }

const state = getDefaultState()

const mutations = {
  SET_USER:(state,payload)=>{
      state.name = payload.name
      state.avatar = payload.avatar
      state.roles = payload.roles
      state.buttons = payload.buttons
      state.routes = payload.routes
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROUTE:(state, asyncRoutes) => {
      state.routes = constantRoutes.concat(asyncRoutes,anyRoute)
      router.addRoutes([...allAsyncRoute,anyRoute])
      console.log(state.routes)
  }
}

const actions = {
  // 用户登录页
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    try {
       const result = await login({username, password})
       setToken(result.token)
       commit('SET_TOKEN',result.token)
    }catch (err){
      return Promise.reject(err.message)
    }
  },

  //获取用户信息
  async getInfo({commit,state}) {
      try{
        const result = await getInfo(state.token)
        commit('SET_USER',result)
        console.log(result)
        //菜单的显示和不显示
        commit('SET_ROUTE',filterAsyncRoutes(cloneDeep(allAsyncRoute),result.routes))
      }catch(error){
        return Promise.reject(error.message)
      }
  },

  // // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  //退出登录
   async logout({ commit,state}){
     try {
       await logout(state.token)
       removeToken()
       resetRouter()
       commit('RESET_STATE')
     }catch (error){
       return Promise.reject(error.message)
     }
   },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

